﻿using myBackupService.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http;

namespace myBackupService.Backup
{
    public class DownloadHttpPlug : PluginBase, IHttpPlugin
    {
        public async Task OnHttpRequest(IHttpSessionClient client, HttpContextEventArgs e)
        {
            var request = e.Context.Request;
            var response = e.Context.Response;
            if (request.IsGet() && request.UrlEquals("/Download"))
            {
                var filePath = BackupConfig.Instance.GetPath(request.Query["pathId"], request.Query["path"]);
                await this.TransferFileToResponse(response, filePath);
                return;
            }

            await e.InvokeNext();
        }
        public async Task TransferFileToResponse(HttpResponse response, string filePath)
        {
            try
            {
             
                if (!File.Exists(filePath))
                {
                    await response.SetStatus(403, $"文件不存在！").AnswerAsync();
                    return;
                }

                using (var fileStream = File.OpenRead(filePath))
                {
                    response.SetContentTypeFromFileName(Path.GetFileName(filePath));
                    response.SetStatus(200, "Success");

                    var len = fileStream.Length;
                    response.ContentLength = len;
                    if(len==0)
                    {
                        await response.WriteAsync(new ReadOnlyMemory<byte>(new byte[0], 0, 0));
                    }
                    else
                    {
                        var buffer = new byte[1024 * 512];
                        while (true)
                        {
                            var readLen = await fileStream.ReadAsync(buffer, 0, buffer.Length);
                            if (readLen == 0)
                            {
                                break;
                            }
                            await response.WriteAsync(new ReadOnlyMemory<byte>(buffer, 0, readLen));
                        }
                    }
                  
                }
            }
            catch (Exception ex)
            {
                await response.SetStatus(403, ex.Message).AnswerAsync();
            }
        }
    }
}
